"""
@description 主窗口界面模块
"""
from PySide6.QtWidgets import (QMainWindow, QWidget, QPushButton, 
                             QTextEdit, QGridLayout, QMessageBox,
                             QVBoxLayout, QHBoxLayout, QLabel,
                             QProgressBar)
from PySide6.QtCore import QThread, Signal
from network_utils import NetworkUtils
from network_optimizer import NetworkOptimizer, SecurityChecker, NetworkRepair
import ctypes
import sys
import platform

class SpeedTestThread(QThread):
    """
    @description 网速测试线程类
    """
    finished = Signal(dict)

    def run(self):
        """
        @description 运行网速测试
        """
        result = NetworkUtils.start_speed_test()
        self.finished.emit(result)

class DiagnoseThread(QThread):
    """
    @description 网络诊断线程类
    """
    finished = Signal(dict)
    progress = Signal(str)

    def run(self):
        """
        @description 运行网络诊断
        """
        self.progress.emit("开始网络诊断...")
        result = NetworkUtils.diagnose_network()
        self.finished.emit(result)

class OptimizeThread(QThread):
    """
    @description 网络优化线程类
    """
    finished = Signal(dict)
    progress = Signal(str)

    def run(self):
        """
        @description 运行网络优化
        """
        self.progress.emit("开始网络优化...")
        result = NetworkOptimizer.optimize_network()
        self.finished.emit(result)

class SecurityCheckThread(QThread):
    """
    @description 安全检查线程类
    """
    finished = Signal(dict)
    progress = Signal(str)

    def run(self):
        """
        @description 运行安全检查
        """
        self.progress.emit("开始安全检查...")
        result = SecurityChecker.check_security()
        self.finished.emit(result)

class MainWindow(QMainWindow):
    """
    @description 主窗口类
    """
    def __init__(self):
        super().__init__()
        self.speed_test_thread = None
        self.diagnose_thread = None
        self.optimize_thread = None
        self.security_thread = None
        self.repair_thread = None
        self.init_ui()

    def init_ui(self):
        """
        @description 初始化用户界面
        """
        self.setWindowTitle('网络工具箱')
        self.setMinimumSize(900, 700)

        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 创建主布局
        main_layout = QVBoxLayout(central_widget)

        # 创建按钮区域
        button_layout = QGridLayout()
        self.create_buttons(button_layout)
        main_layout.addLayout(button_layout)

        # 创建状态显示区域
        self.status_display = QTextEdit()
        self.status_display.setReadOnly(True)
        main_layout.addWidget(self.status_display)

        # 创建进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.hide()
        main_layout.addWidget(self.progress_bar)

        # 显示欢迎信息
        self.status_display.setText("欢迎使用网络工具箱！\n请选择上方按钮执行相应功能。")

    def create_buttons(self, layout):
        """
        @description 创建功能按钮
        @param {QGridLayout} layout - 布局对象
        """
        buttons = [
            ('查看网络信息', self.show_network_info),
            ('网络诊断', self.start_network_diagnose),
            ('网络修复', self.start_network_repair),
            ('网络优化', self.start_network_optimize),
            ('安全检查', self.start_security_check),
            ('DNS测试', self.test_dns),
            ('详细网速测试', self.start_detailed_speed_test),
            ('Ping测试', self.ping_test),
            ('端口测试', self.test_ports)
        ]

        for i, (text, slot) in enumerate(buttons):
            btn = QPushButton(text)
            btn.clicked.connect(slot)
            layout.addWidget(btn, i // 3, i % 3)

    def show_network_info(self):
        """
        @description 显示网络信息
        """
        result = NetworkUtils.get_network_info()
        if result["status"]:
            display_text = "网络接口信息：\n\n"
            for interface, addresses in result["data"].items():
                display_text += f"接口：{interface}\n"
                for addr in addresses:
                    display_text += f"IP地址：{addr['ip']}\n"
                    display_text += f"子网掩码：{addr['netmask']}\n"
                    if addr['broadcast']:
                        display_text += f"广播地址：{addr['broadcast']}\n"
                display_text += "-" * 50 + "\n"
            self.status_display.setText(display_text)
        else:
            self.status_display.setText(result["message"])

    def test_connection(self):
        """
        @description 测试网络连接
        """
        result = NetworkUtils.check_internet_connection()
        self.status_display.setText(f"连接测试结果：\n{result['message']}")

    def ping_test(self):
        """
        @description 执行ping测试
        """
        result = NetworkUtils.ping_test()
        self.status_display.setText(f"Ping测试结果：\n{result['message']}")

    def start_speed_test(self):
        """
        @description 开始网速测试
        """
        self.status_display.setText("正在进行网速测试，请稍候...")
        self.speed_test_thread = SpeedTestThread()
        self.speed_test_thread.finished.connect(self.on_speed_test_complete)
        self.speed_test_thread.start()

    def on_speed_test_complete(self, result):
        """
        @description 网速测试完成回调
        @param {dict} result - 测试结果
        """
        self.status_display.setText(f"网速测试结果：\n{result['message']}")

    def start_network_diagnose(self):
        """
        @description 开始网络诊断
        """
        self.status_display.clear()
        self.status_display.append("正在进行网络诊断...\n")
        self.progress_bar.show()
        self.progress_bar.setRange(0, 0)  # 显示忙碌状态

        self.diagnose_thread = DiagnoseThread()
        self.diagnose_thread.finished.connect(self.on_diagnose_complete)
        self.diagnose_thread.progress.connect(self.update_progress)
        self.diagnose_thread.start()

    def on_diagnose_complete(self, result):
        """
        @description 诊断完成回调
        @param {dict} result - 诊断结果
        """
        self.progress_bar.hide()
        if result["status"]:
            text = "网络诊断结果：\n\n"
            
            # DNS测试结果
            text += "DNS测试结果：\n"
            dns_results = result["tests"]["dns"]["data"]
            for domain, dns_result in dns_results.items():
                if dns_result["status"]:
                    text += f"{domain}: 解析成功，耗时 {dns_result['time']}ms\n"
                    text += f"解析到的IP: {', '.join(dns_result['ips'])}\n"
                else:
                    text += f"{domain}: 解析失败 - {dns_result['error']}\n"
            text += "\n"

            # 网关测试结果
            text += "网关连通性：\n"
            text += result["tests"]["gateway"]["message"] + "\n\n"

            # 互联网连通性
            text += "互联网连通性：\n"
            text += result["tests"]["internet"]["message"] + "\n\n"

            # 端口测试结果
            text += "端口测试结果：\n"
            ports = result["tests"]["ports"]["data"]
            for port, port_result in ports.items():
                text += f"端口 {port}: {port_result['state']}\n"

            self.status_display.setText(text)
        else:
            self.status_display.setText(f"诊断失败：{result['message']}")

    def test_dns(self):
        """
        @description DNS测试
        """
        self.status_display.clear()
        self.status_display.append("正在进行DNS测试...\n")
        
        result = NetworkUtils.test_dns_resolution()
        if result["status"]:
            text = "DNS测试结果：\n\n"
            for domain, dns_result in result["data"].items():
                if dns_result["status"]:
                    text += f"{domain}:\n"
                    text += f"  解析时间: {dns_result['time']}ms\n"
                    text += f"  解析IP: {', '.join(dns_result['ips'])}\n"
                else:
                    text += f"{domain}: 解析失败 - {dns_result['error']}\n"
                text += "\n"
            self.status_display.setText(text)
        else:
            self.status_display.setText(f"DNS测试失败：{result['message']}")

    def start_detailed_speed_test(self):
        """
        @description 开始详细的网速测试
        """
        self.status_display.clear()
        self.status_display.append("正在进行详细网速测试，请稍候...\n")
        self.progress_bar.show()
        self.progress_bar.setRange(0, 0)

        class DetailedSpeedTestThread(QThread):
            finished = Signal(dict)
            
            def run(self):
                result = NetworkUtils.detailed_speed_test()
                self.finished.emit(result)

        self.speed_test_thread = DetailedSpeedTestThread()
        self.speed_test_thread.finished.connect(self.on_detailed_speed_test_complete)
        self.speed_test_thread.start()

    def on_detailed_speed_test_complete(self, result):
        """
        @description 详细网速测试完成回调
        @param {dict} result - 测试结果
        """
        self.progress_bar.hide()
        if result["status"]:
            data = result["data"]
            text = "网速测试详细结果：\n\n"
            text += f"下载速度: {data['download']} Mbps\n"
            text += f"上传速度: {data['upload']} Mbps\n"
            text += f"延迟: {data['ping']} ms\n\n"
            text += "测试服务器信息：\n"
            text += f"名称: {data['server']['name']}\n"
            text += f"位置: {data['server']['location']}\n"
            text += f"延迟: {data['server']['latency']} ms\n"
            self.status_display.setText(text)
        else:
            self.status_display.setText(f"测试失败：{result['message']}")

    def update_progress(self, message):
        """
        @description 更新进度信息
        @param {str} message - 进度信息
        """
        self.status_display.append(message)

    def test_ports(self):
        """
        @description 端口测试
        """
        self.status_display.clear()
        self.status_display.append("正在进行端口测试...\n")
        
        result = NetworkUtils.test_common_ports()
        if result["status"]:
            text = "端口测试结果：\n\n"
            for port, port_result in result["data"].items():
                text += f"端口 {port}: {port_result['state']}\n"
            self.status_display.setText(text)
        else:
            self.status_display.setText(f"端口测试失败：{result['message']}")

    def start_network_optimize(self):
        """
        @description 开始网络优化
        """
        if not NetworkOptimizer.is_admin():
            reply = QMessageBox.question(
                self,
                '权限确认',
                '需要管理员权限才能执行网络优化。是否以管理员身份重新启动程序？',
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                # 请求管理员权限并重启程序
                if platform.system().lower() == 'windows':
                    ctypes.windll.shell32.ShellExecuteW(
                        None, "runas", sys.executable, " ".join(sys.argv), None, 1
                    )
                    self.close()
                return
            return

        reply = QMessageBox.question(
            self,
            '确认',
            '确定要执行网络优化吗？',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.status_display.clear()
            self.status_display.append("正在进行网络优化...\n")
            self.progress_bar.show()
            self.progress_bar.setRange(0, 0)

            self.optimize_thread = OptimizeThread()
            self.optimize_thread.finished.connect(self.on_optimize_complete)
            self.optimize_thread.progress.connect(self.update_progress)
            self.optimize_thread.start()

    def on_optimize_complete(self, result):
        """
        @description 优化完成回调
        @param {dict} result - 优化结果
        """
        self.progress_bar.hide()
        if result["status"]:
            text = "网络优化结果：\n\n"
            
            # DNS优化结果
            text += "DNS优化：\n"
            text += result["optimizations"]["dns"]["message"] + "\n\n"
            
            # TCP优化结果
            text += "TCP参数优化：\n"
            tcp_results = result["optimizations"]["tcp"]["data"]
            for item in tcp_results:
                text += f"{item}\n"
            text += "\n"
            
            # 网络适配器优化结果
            text += "网络适配器优化：\n"
            adapter_results = result["optimizations"]["adapter"]["data"]
            for item in adapter_results:
                text += f"{item}\n"
                
            self.status_display.setText(text)
        else:
            self.status_display.setText(f"优化失败：{result['message']}")

    def start_security_check(self):
        """
        @description 开始安全检查
        """
        self.status_display.clear()
        self.status_display.append("正在进行安全检查...\n")
        self.progress_bar.show()
        self.progress_bar.setRange(0, 0)

        self.security_thread = SecurityCheckThread()
        self.security_thread.finished.connect(self.on_security_check_complete)
        self.security_thread.progress.connect(self.update_progress)
        self.security_thread.start()

    def on_security_check_complete(self, result):
        """
        @description 安全检查完成回调
        @param {dict} result - 检查结果
        """
        self.progress_bar.hide()
        if result["status"]:
            text = "安全检查结果：\n\n"
            
            # 开放端口检查结果
            text += "开放端口检查：\n"
            ports = result["checks"]["ports"]["data"]
            if ports:
                text += f"发现 {len(ports)} 个开放端口：\n"
                for port in ports:
                    text += f"- 端口 {port}\n"
            else:
                text += "未发现开放端口\n"
            text += "\n"
            
            # 防火墙状态
            text += "防火墙状态：\n"
            firewall = result["checks"]["firewall"]["data"]
            for profile, status in firewall.items():
                text += f"{profile}: {'启用' if status else '禁用'}\n"
            text += "\n"
            
            # 活动连接
            text += "活动网络连接：\n"
            connections = result["checks"]["connections"]["data"]
            for conn in connections:
                text += f"进程: {conn['process_name']} (PID: {conn['pid']})\n"
                text += f"本地地址: {conn['local_address']}\n"
                text += f"远程地址: {conn['remote_address']}\n"
                text += f"状态: {conn['status']}\n"
                text += "-" * 50 + "\n"
                
            self.status_display.setText(text)
        else:
            self.status_display.setText(f"安全检查失败：{result['message']}")

    def start_network_repair(self):
        """
        @description 开始网络修复
        """
        reply = QMessageBox.question(
            self,
            '确认',
            '网络修复可能需要重启网络服务，是否继续？',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.status_display.clear()
            self.status_display.append("正在进行网络修复...\n")
            self.progress_bar.show()
            self.progress_bar.setRange(0, 0)

            class RepairThread(QThread):
                finished = Signal(dict)
                progress = Signal(str)
                
                def run(self):
                    # 先进行诊断
                    diagnosis_result = NetworkOptimizer.diagnose_network()
                    self.progress.emit("诊断完成，开始修复...")
                    # 根据诊断结果进行修复
                    repair_result = NetworkRepair.repair_network(diagnosis_result)
                    self.finished.emit(repair_result)

            self.repair_thread = RepairThread()
            self.repair_thread.finished.connect(self.on_repair_complete)
            self.repair_thread.progress.connect(self.update_progress)
            self.repair_thread.start()

    def on_repair_complete(self, result):
        """
        @description 修复完成回调
        @param {dict} result - 修复结果
        """
        self.progress_bar.hide()
        
        # 记录日志
        self.log_manager.log_operation("网络修复完成", result)
        
        # 如果配置了保存报告，则保存修复报告
        if self.config_manager.get('save_reports'):
            self.report_manager.save_report("repair", result)
        
        if result["status"]:
            text = "网络修复结果：\n\n"
            
            for repair_type, repair_result in result["repairs"].items():
                text += f"{repair_type.upper()} 修复：\n"
                if repair_result["status"]:
                    for repair in repair_result.get("repairs", []):
                        text += f"✓ {repair}\n"
                else:
                    text += f"✗ {repair_result['message']}\n"
                text += "\n"
                
            self.status_display.setText(text)
            
            # 提示可能需要重启
            QMessageBox.information(
                self,
                '修复完成',
                '网络修复已完成，建议重启计算机以使所有更改生效。'
            )
        else:
            self.status_display.setText(f"修复失败：{result['message']}")
        
        self.statusBar().showMessage(result["message"]) 